package com.duzhuo.springsecurity.handler;

import com.duzhuo.springsecurity.config.TokenManager;
import com.duzhuo.springsecurity.utils.R;
import com.duzhuo.springsecurity.utils.ResponseUtil;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.security.auth.Subject;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;

public class PhoneFilter extends AbstractAuthenticationProcessingFilter {
    public PhoneFilter(AuthenticationManager authenticationManager){
        super(new AntPathRequestMatcher("/myPhoneLogin", "POST"));
        this.setAuthenticationManager(authenticationManager);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
       //todo check login
        Authentication authentication = new Authentication() {
            @Override
            public String getName() {
                return "xal";
            }

            @Override
            public boolean implies(Subject subject) {
                return Authentication.super.implies(subject);
            }

            @Override
            public Collection<? extends GrantedAuthority> getAuthorities() {
                return null;
            }

            @Override
            public Object getCredentials() {
                return null;
            }

            @Override
            public Object getDetails() {
                return "details";
            }

            @Override
            public Object getPrincipal() {
                return null;
            }

            @Override
            public boolean isAuthenticated() {
                return false;
            }

            @Override
            public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {

            }
        };
        return authentication;
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        SecurityContextHolder.getContext().setAuthentication(authResult);
        ResponseUtil.out(response, R.ok().data(TokenManager.TOKEN_HEADER, TokenManager.TOKEN_PREFIX + "Phone token"));
    }
}
